package me.lijf.mqlite.redis.message;

import lombok.extern.log4j.Log4j2;
import me.lijf.mqlite.redis.stream.StreamQueConfig;
import me.lijf.mqlite.redis.stream.RedisMqStream;
import me.lijf.mqlite.redis.stream.RedisStreamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("/msg")
public class MessagePublisher {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${redis.message.que}")
    private String que;
    @Value("${redis.message.topic}")
    private String topic;
    @Autowired
    private StreamQueConfig yml;
    @Autowired
    private RedisStreamUtil util;


    @RequestMapping("/push")
    public Object push(){
        Long stamp=new Date().getTime();
        redisTemplate.opsForList().leftPush(que,stamp.toString());
        String message="向队列${topic}发送${message}"
                .replace("${topic}",que)
                .replace("${message}",String.valueOf(stamp));
        log.info(message);
        return message;
    }

    @RequestMapping("/send")
    public Object send(){
        Long stamp=new Date().getTime();
        redisTemplate.convertAndSend(topic,stamp);
        String message="向频道${topic}发送${message}"
                .replace("${topic}",topic)
                .replace("${message}",String.valueOf(stamp));
        log.info(message);
        return message;
    }

    @RequestMapping("/stream")
    public Object inStream(){
        Map<String,Object> map=new HashMap<>();
        StringBuffer b=new StringBuffer();
        List<RedisMqStream> streams = yml.getStreams();
        for(RedisMqStream stream:streams) {
            String streamKey=stream.getName();
            Long stamp=new Date().getTime();
            map.put("body",String.valueOf(stamp));
            util.write(streamKey,map);
            String message = "向流${topic}发送${message}"
                    .replace("${topic}", streamKey)
                    .replace("${message}", map.get("body").toString());
            log.info(message);
            b.append(message).append("<br/>\n");
        }
        return b.toString();

    }
}
